const express=require('express')
const app=express()
const cors=require('cors')
const joi=require('joi')

app.use(cors())
app.use(express.urlencoded({extends:false}))
// const bodyParse=require('body-parser')
// app.use(bodyParse.urlencoded({extends:false}))
// app.use(bodyParse.json())


app.use((req,res,next)=>{   //处理失败结果
    //status=0 成功 status=1 失败 
    res.cc=(err,status=1)=>{
        res.send({
            status,
            message:err instanceof Error ? err.message:err,
        })
    }
    next()
})

const config=require(__dirname+'/config')
const expressJWT=require('express-jwt')
app.use(expressJWT({secret:config.jwtSecretKey,algorithms:['HS256']}).unless({ path: [/^\/api\//] }))

const userRouter=require(__dirname+'/router/user.js')
app.use('/api',userRouter)
app.get('/user',(req,res)=>{
    res.send({status:0,message:'再登录成功'})
})
app.use((err,req,res,next)=>{
    if(err instanceof joi.ValidationError) return res.cc(err)
    if(err.name === 'UnauthorizedError') return res.cc('身份认证失败')
    res.cc(err)
})

app.listen(3007,()=>{
    console.log('api server running at http://127.0.0.1:3007')
})